﻿using System.Threading;
using Microsoft.Phone.Net.NetworkInformation;

namespace System.Net
{
    /// <summary>
    /// <see cref="INetworkStateManager">INetworkStateManager</see> implementation.
    /// </summary>
    public class NetworkStateManager : INetworkStateManager
    {
        #region Implementation of INetworkManager

        /// <summary>
        ///Validates network state. If <paramref name="raiseException">raiseException</paramref> specified and true - throws exception.
        /// </summary>
        /// <param name="raiseException"></param>
        /// <exception cref="NetworkNotAvailableException"></exception>
        public void ValidateNetworkState(bool raiseException = true)
        {
            if (!IsNetworkConnected && raiseException)
            {
                throw new NetworkNotAvailableException();
            }
        }

        /// <summary>
        /// Gets is network connected state asynchronously
        /// </summary>
        /// <param name="callBack"></param>
        public void GetIsNetworkAvailableAsync(Action<bool> callBack)
        {
            ThreadPool.QueueUserWorkItem(waitCallback => callBack(IsNetworkConnected));
        }

        /// <summary>
        /// Gets is network connected state.
        /// </summary>
        public bool IsNetworkConnected
        {
            get
            {
                return NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
            }
        }

        #endregion
    }
}